package com.ruoyi.task.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.minio.MinioTemplate;
import com.ruoyi.task.domain.TaskSub;
import com.ruoyi.task.domain.dto.TaskInfoDTO;
import com.ruoyi.task.domain.vo.TaskInfoVO;
import com.ruoyi.task.mapper.TaskSubMapper;
import com.ruoyi.task.service.TaskSubService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipOutputStream;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

@Service
public class TaskSubServiceImpl implements TaskSubService {

    @Autowired
    TaskSubMapper taskSubMapper;
    @Autowired
    MinioTemplate minioTemplate;

    @Override
    public int submitTask(TaskSub taskSub) {
        LoginUser loginUser = getLoginUser();  //通过get方法拿到参数
        SysUser sysUser = loginUser.getUser();
        taskSub.setStudentId(sysUser.getStudentId());
        taskSub.setSubmissionTime(new Date());
        System.out.println(taskSub);
        return taskSubMapper.subTask(taskSub);
    }

    @Override
    public List<TaskInfoVO> gettaskInfo(TaskInfoDTO taskInfoVO) {

        return taskSubMapper.seletInfoList(taskInfoVO);
    }

    @SneakyThrows
    @Override
    public void exportFile(List<Integer> ids, HttpServletResponse response) {
        List<TaskInfoVO> list = taskSubMapper.seletByIds(ids);

        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"files.zip\"");
        response.setContentType("application/zip");
        response.setHeader(HttpHeaders.TRANSFER_ENCODING, "chunked"); // 添加 chunked encoding header

        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (TaskInfoVO taskInfoVO : list) {
                String path = taskInfoVO.getFilePath();
                String objectName = path.substring(path.indexOf("file")); // 获取对象名称
//                System.out.println(objectName);
                // 将文件添加到 ZIP 文件
                String filename = generateCustomFileName(taskInfoVO);
                minioTemplate.addFileToZip(objectName, zipOut, filename);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String generateCustomFileName(TaskInfoVO taskInfoVO) {
        String prefix = taskInfoVO.getFilePath().substring(taskInfoVO.getFilePath().lastIndexOf(".") + 1);
        String filename = taskInfoVO.getTaskName() + "_" + taskInfoVO.getClassName() + "_" + taskInfoVO.getStudentName() + "_" + taskInfoVO.getStudentId() +
                "." + prefix;
        return filename;
    }
}
